package server.command;

import java.util.Iterator;
import java.util.List;

import org.apache.mina.core.session.IoSession;

import server.IDispatcher;
import server.Message;
import server.core.User;
import server.dao.DAOFactory;
import server.dao.UserDAO;

public class Login extends Command {

	private Login() {
	}

	public static Command getInstance() {
		if (instance == null)
			instance = new Login();
		return instance;
	}

	@Override
	public synchronized void execute(IoSession session, List<String> parameters, IDispatcher dispatcher) {
		DAOFactory df = DAOFactory.getInstance();
		UserDAO userDAO = df.getUserDAO();
		String result = "ERROR1"; //Operation failed

		if (parameters.size() == 2) {
			Iterator<String> it = parameters.iterator();
			String username = it.next();
			String password = it.next();
			if (userDAO.checkUser(username, password).equals("true")) {
				if (dispatcher.containsSessionForUser(username)) {
					result = "ERROR2"; //Somebody already logged in with this username!
				} else {
					result = "OK";
					User user = userDAO.getUserByUserName(username);
					session.setAttribute("user", user);
					dispatcher.addSession(user.getUsername(), session);
				}
			}
		} else {
			result = "ERROR3"; //Missing parameters!
		}
		session.write(new Message("LOGIN:" + result));

	}
}
